package com.aner.tester.utils;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * custom logger utility
 *
 * @author aner
 * @version 1.0
 * @date 2020/12/26 22:56
 */
public class LoggerUtils {

    private static LoggerContext loggerContext;

    private static ConsoleAppender<ILoggingEvent> consoleAppender;

    public static Logger getLogger(Class cls){
        ch.qos.logback.classic.Logger rootLogger = loggerContext.getLogger(cls.getName());
        rootLogger.setLevel(Level.INFO);
        rootLogger.addAppender(consoleAppender);
        return rootLogger;
    }

    /**
     * init logger
     */
    static {
        loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        // remove all configuration information
        loggerContext.reset();
        consoleAppender = new ConsoleAppender<>();
        consoleAppender.setContext(loggerContext);
        consoleAppender.setName("console");
        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        // encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n");
        encoder.setPattern("[%level] %msg%n");
        encoder.setCharset(Charset.forName("UTF-8"));
        encoder.setContext(loggerContext);
        encoder.start();
        consoleAppender.setEncoder(encoder);
        consoleAppender.start();
    }

    public static void main(String[] args) {
        LoggerUtils.getLogger(LoggerUtils.class).info("this is test log.");
    }
}
